package com.simple.gateway.common.authorization.auth;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.simple.gateway.common.authorization.GatewayAuthorizingToken;
import com.simple.gateway.common.interfaces.GatewayAuth;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;

/**
 * 项目: simple-gateway
 * <p>
 * 功能描述: 授权实现类
 *
 * @author: WuChengXing
 * @create: 2023-08-05 23:12
 **/
public class TokenAuthService implements GatewayAuth {

    private final Subject subject;

    public TokenAuthService() {
        // 1. 获取 SecurityManager 工厂，此处使用 shiro.ini 配置文件初始化 SecurityManager
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        // 2. 得到 SecurityManager 实例 并绑定给 SecurityUtils
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);
        // 3. 得到 Subject 及 Token
        this.subject = SecurityUtils.getSubject();
    }

    @Override
    public boolean validate(String authExtension) {
        JSONObject jsonObject = JSON.parseObject(authExtension);
        String id = (String) jsonObject.get("user_name");
        String token = (String) jsonObject.get("token");
        try {
            // 身份验证
            subject.login(new GatewayAuthorizingToken(id, token));
            // 返回结果
            return subject.isAuthenticated();
        } finally {
            // 退出
            subject.logout();
        }
    }
}
